import 'normalize.css/normalize.css';
import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import VueRouter from 'vue-router'
import { sync } from 'vuex-router-sync'
import store from './vuex'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import './style/index.scss';
import './style/layout.scss';
import util from './tools/util/util'
import * as filters from './filters'
import { routes } from './routes'
import errLog from './vuex/errLog'
import  VueQuillEditor from 'vue-quill-editor'

// import Mock from './mock'
// Mock.bootstrap();
Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(VueQuillEditor)
// Vue.use(messageBoxs)
NProgress.configure({
	showSpinner: false
});
const router = new VueRouter({
	routes
})
sync(store, router)
router.beforeEach((to, from, next) => {
	NProgress.start();
	if(to.meta.noToken) {
		next();
	} else {
		if(store.getters.token) { // 判断是否有token
			if(to.path != '/' && !store.getters.name) {
				document.getElementById("loading").className = '';
				store.dispatch('getOperation', to.path)
				store.dispatch('getinfo').then(data => {
					store.dispatch('GenerateRoutes', {
						authMenu: data.obj.authMenu
					}).then(() => { // 生成可访问的路由表
						console.log(store.getters.addRouters)

						router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表

						Vue.nextTick(() => {
							next({
								path: to.path,
								query: to.query,
								params: to.params
							});
						})
					})
				}).catch(err => {
					console.log(err);
				});
			} else {
				next();
			}
			NProgress.done();
		} else {
			console.log(to, from)
			if(to.path === '/') {
				if(to.query.logout == 'logout') {
					// let url='/';
					// url+=to.query.redirect?'?redirect'+'='+to.query.redirect:'';
					//
					// console.log(to.query,url)
					location.href = '/';
				} else if(to.query.redirect) {
					let url = '/';
					console.log(to.query.redirect)
					url += to.query.redirect ? '?redirect' + '=' + to.query.redirect : '';
					util.setLoca('redirect', to.query.redirect)
					console.log(to.query, url)
					location.href = '/';
				} else {
					next();
				}
			} else if(to.path === '/ltIe') {
				next();
			} else {
				next('/');
				Vue.prototype.$message.error('请先登录哈！')
				NProgress.done(); // 在hash模式下 改变手动改变hash 重定向回来 不会触发afterEach 暂时hack方案 ps：history模式下无问题，可删除该行！
			}
		}
	}
})

router.afterEach(route => {
	NProgress.done();
	if(document.getElementById("loading").className == '') {
		window.hideLoadingPage();
	}
});

import axios from 'axios';
import qs from 'qs';
axios.defaults.timeout = 20000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.interceptors.request.use(
	config => {
		NProgress.start();
		let token = store.getters.token;
		if(token) { // 判断是否存在token，如果存在的话，则每个http header都加上token
			// console.log(`token ${token}`,router,store.state.route.fullPath)
			config.headers.token = `${token}`;
			// console.log(config,store.state.route.fullPath)
			// if(config.data){
			//   config.data.path=store.state.route.fullPath
			// }else{
			//   config.data={
			//     path:store.state.route.fullPath
			//   }
			// }
		}
		config.data = qs.stringify(config.data);
		return config;
	},
	error => {
		console.log(error)
		store.commit('commonLoading', false)
		Vue.prototype.$message.error('服务器繁忙，请休息一下，稍候重试！')
		NProgress.done();
		return Promise.reject(error);
	}
);
axios.interceptors.response.use(
	response => {
		NProgress.done();
		store.commit('commonLoading', false)
		return response.data;
	},
	error => {
		switch(error.response && error.response.status) {
			case 401:
				Vue.prototype.$message('登录搜权已过期，请重新登录！')
				// router.replace({
				//   path: '/',
				//   query: {redirect:encodeURI(router.currentRoute.fullPath)}
				// });
				store.dispatch('LogOut').then(() => {
					// console.log(store, router)
					router.replace({
						path: '/',
						query: {
							redirect: encodeURI(router.currentRoute.fullPath)
						}
					});
				});
				// location.reload();
				break;
			case 403:
				Vue.prototype.$message.error('您没有权限访问该页面，请联系管理员！')
				router.replace({
					path: '/404'
				})
				break;
			default:
				Vue.prototype.$message.error('服务器繁忙，请休息一下，稍候重试！');
				break;
		}
		NProgress.done();
		store.commit('commonLoading', false)
		axios.CancelToken.source().cancel();
		return Promise.reject(error);
	}
)
Vue.prototype.$http = axios
Vue.http = axios
Vue.config.devtools = true;
if(process.env.NODE_ENV === 'production') {
	// 生产环境错误日志
	Vue.config.errorHandler = function(err, vm) {
		console.log(err, window.location.href)
		errLog.pushLog({
			err,
			url: window.location.href,
			vm
		})
	}
	console.log = function() {}
	console.warn = function() {}
	Vue.config.productionTip = false
	Vue.config.devtools = false;
}
Object.keys(filters).forEach(key => {
	Vue.filter(key, filters[key])
})
Vue.prototype.baseJs = util;
new Vue({
	router,
	store,
	render: h => h(App)
}).$mount('#app')